package demo;

import java.util.Scanner;

//斐波那契数列（迭代方法）
public class Fib{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入项数：");
        int num = scanner.nextInt();
        int ret = fib(num);
        int ret1 = fibSum(num);
        System.out.println("该项数的值为："+ret);
        System.out.println("前n项数和为："+ret1);
        scanner.close();
    }
    public static int fib(int n){
        if(n==1||n==2){
            return 1;
        }
        int f1 = 1;
        int f2 = 1;
        int f3 = 1;
        //注意i从3开始
        for(int i = 3;i<=n;i++){
            f3 = f1 + f2;
            f1 = f2;
            f2 = f3;
        }
        return f3;
    }
    public static int fibSum(int n) {
        int sum = 0;
        //循环累加第1项到第n项的所有值
        //i从1开始，因为第一项为1
        for (int i = 1; i <= n; i++) {
            sum += fib(i);//fib()放的是i
        }
        return sum;
    }
}
